<?php

namespace App\Traits;
use App\Notifications\ResetPassword as ResetPasswordNotification;
use App\User;
use Illuminate\Http\Request;
use Validator;

trait ResetPassword {

	public function sendResetMail(Request $request) {
		$this->validate($request, [
			'email' => 'required|email',
		]);
		$user = $this->model->getUserByEmail($request->email);
		if (!$user) {
			abort(422, 'the account is not find');
		}
		$user->notify(new ResetPasswordNotification($user));
		return $this->response->withNoContent();
	}

	public function resetMailPassword($token) {
		$user = (new User)->where('confirm_code', $token)->firstOrFail();
		return view('plugs.reset', compact('token', 'user'));
	}

	public function resetMailPasswordAction(Request $request) {
		$validate = Validator::make($request->all(), [
			'email' => 'required|email',
			'token' => 'required|min:32|max:32',
			'password' => 'required|min:6|max:18|confirmed',
		]);
		$user = (new User)->where('email', $request->email)->first();
		if (!$user) {
			$validate->errors()->add('email', 'we didn\'t find the email in our website!');
			return redirect()->back()->withErrors($validate);
		}
		if ($user->confirm_code != $request->token) {
			$validate->errors()->add('email', 'please input your email!');
			return redirect()->back()->withErrors($validate);
		}
		$user->password = $request->password;
		$user->save();
		if (property_exists($this, 'response')) {
			return $this->response->withNoContent();
		}
		return view('plugs.success', compact('user'));
	}

	public function resetPwd(Request $request) {
		$this->validate($request, [
			'old_password' => 'required|min:6|max:18|',
			'password' => 'required|min:6|max:18|confirmed',
		]);
		$user = Auth::user();
		if (!Hash::check($request->input('old_password'), $user->password)) {
			abort(422, 'password is error');
		}
		$user->password = $request->password;
		$user->save();
		return $this->response->withNoContent();
	}
}